package com.yc154.springmvc.web;

import com.yc.starter.login.biz.BizException;
import com.yc154.springmvc.biz.ServiceException;
import com.yc154.springmvc.po.User;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@RestController
public class UserAction {

    @RequestMapping(value = "/reg",
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public Map reg1(@Valid User user, BindingResult result){
        System.out.println("user = " + user);
        if (result.hasErrors()) {
            throw new ServiceException("字段验证错误", result.getAllErrors());
        } else {
            return Map.of("code", 1,
                    "msg", "注册成功",
                    "data", user);
        }
    }

    @RequestMapping(path = "/reg",
            consumes = MediaType.APPLICATION_JSON_VALUE)
    public Map reg2(@RequestBody @Valid User user, BindingResult result){
        System.out.println("user = " + user);
        if (result.hasErrors()) {
            throw new ServiceException("字段验证错误", result.getAllErrors());
        } else {
            return Map.of("code", 1,
                    "msg", "注册成功",
                    "data", user);
        }
    }

    @PostMapping("uploadHead")
    public Map uploadHead(@RequestParam("head") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String prefix = UUID.randomUUID().toString();
        String fileName = prefix + suffix;
        String uploadDir = "E:\\录屏\\154\\0914";
        String filePath = uploadDir + "/" + fileName;
        file.transferTo(new File(filePath));
        String webPath = "/upload/" + fileName;
        return Map.of("code",1,
                "msg","文件上传成功!",
                "data",webPath);
    }

}
